package com.spring.graphql.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.Objects;

@Configuration
public class RedisConfig {

    private static final String REDIS_HOST_KEY = "spring.redis.host";
    private static final String REDIS_HOST_PORT_KEY = "spring.redis.port";

    @Resource
    private Environment environment;

    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        return new JedisConnectionFactory(new RedisStandaloneConfiguration(
                Objects.requireNonNull(environment.getProperty(REDIS_HOST_KEY)),
                environment.getProperty(REDIS_HOST_PORT_KEY, Integer.class, 6379)
        ));
    }

    @Bean
    public StringRedisTemplate redisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory());
        // explicitly enable transaction support
        template.setEnableTransactionSupport(true);
        return template;
    }
}
